package com.bulletelc.apollopre;

import android.app.Application;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.NonNull;
import android.support.multidex.MultiDex;
import android.text.TextUtils;

import com.bulletelc.apollopre.constants.GlobalConfig;
import com.bulletelc.apollopre.constants.SPKey;
import com.bulletelc.apollopre.db.DBHelper;
import com.bulletelc.apollopre.manager.OkGoManager;
import com.bulletelc.apollopre.utils.SharedPreferencesUtil;
import com.bulletelc.apollopre.utils.exception.CatchHandler;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreater;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreater;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.uuzuche.lib_zxing.activity.ZXingLibrary;
import com.zhy.autolayout.config.AutoLayoutConifg;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

/**
 * author: lhl
 * time  : 2017/10/15
 * desc  : application
 */

public class MyApplication extends Application {

    //PushAgent mPushAgent;

    //static 代码段可以防止内存泄漏
    //初始化SmartRefreshLayout下拉刷新控件
    static {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreater(new DefaultRefreshHeaderCreater() {
            @NonNull
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                layout.setPrimaryColorsId(R.color.white, R.color.gray);//设置全局主题颜色

                return new ClassicsHeader(context).setSpinnerStyle(SpinnerStyle.Translate);//指定为经典Header，默认是 贝塞尔雷达Header
            }
        });

        //设置全局的footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreater(new DefaultRefreshFooterCreater() {
            @NonNull
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //layout.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setSpinnerStyle(SpinnerStyle.Translate);
            }
        });

    }

    private static MyApplication appContext;
    /**
     * 全局的token ,使用时需判断是否为null
     */
    private static String token;
    private static String userId;

    private SQLiteDatabase readDB;

    private SQLiteDatabase writeDB;

    /**
     * IWXAPI是第三方app和微信通信的openapi接口
     */
    public static IWXAPI iwxapi;

    @Override
    public void onCreate() {
        super.onCreate();

        appContext =this;

        initToken();
        initUserId();
        initException();
        initBugly();
        initAutoLayout();
        initZXing();
        initOkGo();
        regToWx();
        //initUmeng();
    }

    /**
     * 重写该方法,调用 MultiDex.install(this) 以启用 Dalvik 可执行文件分包
     * @param base
     */
    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    /**
     * 初始化token
     */
    private void initToken() {
        token = SharedPreferencesUtil.getString(this, SPKey.SP_ACCESS_TOKEN);
    }

    /**
     * 初始化UserId
     */
    private void initUserId() {
        userId = SharedPreferencesUtil.getString(this, SPKey.SP_USER_ID);
    }



    /**
     * 将异常捕获类设置到主线程上,该做法和bugly冲突
     */
    private void initException(){
        CatchHandler handler = new CatchHandler();
        Thread thread = Thread.currentThread();
        thread.setUncaughtExceptionHandler(handler);

    }

    /**
     * 初始化bugly
     */
    private void initBugly() {
        //增加上报进程控制

        Context context=getApplicationContext();
        //获取当前包名
        String packageName=context.getPackageName();
        //获取当前进程名
        String processName = getProcessName(android.os.Process.myPid());
        //设置是否为上报进程
        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(context);
        strategy.setUploadProcess(processName == null || processName.equals(packageName));

        //第三个参数为SDK调试模式开关,建议在测试阶段建议设置成true，发布时设置为false。
        CrashReport.initCrashReport(getApplicationContext(),GlobalConfig.BUGLY_APP_ID,true,strategy);
    }

    /**
     * 初始化AutoLayout
     */
    private void initAutoLayout(){
        //AutoLayout,使用设备的物理高度
        AutoLayoutConifg.getInstance().useDeviceSize();
    }

    /**
     * 初始化zxing
     */
    private void initZXing(){
        ZXingLibrary.initDisplayOpinion(this);
    }

    /**
     * 初始化okGo库
     */
    private void initOkGo() {
        OkGoManager.getInstance().initOkGo(this);
    }

    /**
     * 初始化数据库(原生API操作)
     */
    private void initDB(){
        //打开数据库
        DBHelper dbHelper = new DBHelper(this,GlobalConfig.DATABASE_NAME,null,GlobalConfig.DATABASE_VERSION);
        readDB=dbHelper.getReadableDatabase();
        writeDB=dbHelper.getWritableDatabase();
    }
    /**
     * 注册到微信
     */
    private void regToWx() {
        iwxapi =WXAPIFactory.createWXAPI(this, GlobalConfig.WX_API_APP_ID,true);
        //将应用的appId注册到微信
        iwxapi.registerApp(GlobalConfig.WX_API_APP_ID);
    }


    /**
     * 获取 application实例
     * @return
     */
    public static MyApplication getInstance() {
        return appContext;
    }

    public SQLiteDatabase getReadDB() {
        return readDB;
    }

    public SQLiteDatabase getWriteDB() {
        return writeDB;
    }

    public IWXAPI getIwxapi() {
        return iwxapi;
    }

    public static String getToken() {
        return token;
    }

    public static void setToken(String token) {
        MyApplication.token = token;
    }

    public static String getUserId() {
        return userId;
    }

    public static void setUserId(String userId) {
        MyApplication.userId = userId;
    }

    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    private static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }

}
